#include "Comm.hpp"
#include "Log.hpp"
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <string.h>


using namespace LogMudule;

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        std::cout << argv[0] << "serverip,serverport" <<endl;
        return 1;
    }
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "socket failed " << strerror(sockfd);
        exit(SOCKERR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    //创建套接字成功
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;

    //主机转网络
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    //发送消息
    while(true)
    {
        std::cout << "ehco#: ";
        std::string message;
        getline(std::cin,message);

        ::sendto(sockfd,message.c_str(),message.size(),0,(const sockaddr*)&server,sizeof(server));

        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);

        char buffer[1024];
        int n = recvfrom(sockfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&temp,&len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer <<std::endl;
        }
    }
    return 0;
}